import os,shutil
import numpy as np
import cv2
from PIL import Image

def letterbox_image(image, size):
    iw, ih = image.size
    w, h = size
    scale = min(w/iw, h/ih)
    nw = int(iw*scale)
    nh = int(ih*scale)

    image = image.resize((nw,nh), Image.BICUBIC)
    # new_image = Image.new('RGB', size, (128,128,128))
    new_image = Image.new('RGB', size, (0,0,0))
    new_image.paste(image, ((w-nw)//2, (h-nh)//2))
    return new_image

def search_files(directory):
    directory = os.path.normpath(directory)

    print(directory)

    objects = {}
    for curdir, subdirs, files in os.walk(directory):
        for file in files:
            if file.endswith(('.png','jpeg','jpg','bmp')):
                label = curdir.split(os.path.sep)[-1]
                if label not in objects:
                    objects[label] = []
                path = os.path.join(curdir, file)
                objects[label].append(path)
    return objects
if __name__ == "__main__":
    # train_samples = search_files('/root/image/car image/chest/seg')
    # train_samples = search_files(r'/home/user/桌面/fu_2022_6_24/2022-7-6/2022-7-6/bicycle2/motorbike')
    # train_samples = search_files(r'E:\dataset_perfect\all_need_test\add_new\car_new2\car')
    train_samples = search_files(r'E:\dataset_perfect\all_need_test\add_new\table_new\diningtable')

    # 
    i=0
    print(train_samples)

    for label, filenames in train_samples.items():
        for filename in filenames:
            i=i+1
            try:
                img = Image.open(filename)
                # new_img = letterbox_image(img, (224, 224))
                new_img = letterbox_image(img, (640, 640))
                new_img.save(filename)
                # new_part_name="E:\\dataset_perfect\\motorbike2\\new_"+str(i)+'.jpg'
                new_part_name="E:\\dataset_perfect\\all_need_test\\add_new\\change_table_new\\"+"new"+str(i)+'.jpg'
                shutil.copy2(filename, new_part_name)

            except:
                print(3333)
                # shutil.move(filename,r"E:\\dataset_perfect\\杂项\\motorbike2")
                shutil.move(filename,r"E:\\dataset_perfect\\all_need_test\\upload_all\\杂项")
